package com.car.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.car.mapper.CarMapper;
import com.car.mapper.UserMapper;
import com.car.pojo.Car;
import com.car.pojo.CarQueryParam;
import com.car.pojo.PageResult;
import com.car.pojo.User;
import com.car.service.CarService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 汽车服务实现类
 */
@Slf4j
@Service
public class CarServiceImpl implements CarService {

    @Autowired
    private CarMapper carMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public Car getInfo(Integer id) {
        Car car = carMapper.selectById(id);
        if (car != null && car.getUserId() != null) {
            User user = userMapper.selectById(car.getUserId());
            if (user != null) {
                car.setUserName(user.getName());
            }
        }
        return car;
    }

    @Override
    public List<Car> getCarsByUserId(Integer userId) {
        log.info("根据用户ID查询车辆列表: userId={}", userId);
        return carMapper.selectByUserId(userId);
    }

    @Override
    public Integer getCarsCountByUserId(Integer userId) {
        log.info("根据用户ID查询车辆数量: userId={}", userId);
        return carMapper.selectByUserIdCar(userId);
    }

    @Override
    public boolean isPlateNumberExists(String plateNumber, Integer excludeId, Integer userId) {
        log.info("检查车牌号是否已存在: plateNumber={}, excludeId={}, userId={}", plateNumber, excludeId, userId);
        int count = carMapper.countByPlateNumberExcludeId(plateNumber, excludeId, userId);
        return count > 0;
    }

    @Override
    public PageResult<Car> page(CarQueryParam param) {
        //1. 设置分页参数
        PageHelper.startPage(param.getPage(), param.getPageSize());

        //2. 执行查询
        List<Car> carList = carMapper.list(param);
        
        //3. 为每个汽车对象填充用户姓名
        for (Car car : carList) {
            if (car.getUserId() != null) {
                User user = userMapper.selectById(car.getUserId());
                if (user != null) {
                    car.setUserName(user.getName());
                }
            }
        }

        //4. 解析查询结果并封装
        Page<Car> p = (Page<Car>) carList;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void save(Car car) throws Exception {
        log.info("新增汽车: {}", car);
        car.setCreateTime(LocalDateTime.now());
        car.setUpdateTime(LocalDateTime.now());
        carMapper.insert(car);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void addCar(Car car) {
        log.info("添加用户车辆: {}", car);
        car.setCreateTime(LocalDateTime.now());
        car.setUpdateTime(LocalDateTime.now());
        carMapper.insert(car);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void update(Car car) {
        log.info("修改汽车: {}", car);
        car.setUpdateTime(LocalDateTime.now());
        carMapper.updateById(car);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void updateCar(Car car) {
        log.info("更新用户车辆信息: {}", car);
        car.setUpdateTime(LocalDateTime.now());
        carMapper.updateById(car);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void delete(List<Integer> ids) {
        log.info("删除汽车: {}", ids);
        carMapper.deleteByIds(ids);
    }

    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void deleteCar(Integer id) {
        log.info("删除用户车辆: id={}", id);
        carMapper.delete(id);
    }

    @Override
    public List<Car> list() {
        List<Car> carList = carMapper.queryAll();
        
        //为每个汽车对象填充用户姓名
        for (Car car : carList) {
            if (car.getUserId() != null) {
                User user = userMapper.selectById(car.getUserId());
                if (user != null) {
                    car.setUserName(user.getName());
                }
            }
        }
        
        return carList;
    }
}